package com.hue.netty.day03.rpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.concurrent.Callable;

public class NettyClientHandler extends SimpleChannelInboundHandler<String> implements Callable {
    private ChannelHandlerContext ctx = null;
    private String result = null;
    private String para = null;

    public void setPara(String para) {
        this.para = para;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //接收到服务端的结果
        result = msg;
        notify();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接成功");
        this.ctx = ctx;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public synchronized Object call() throws Exception {
        //发送数据
        ctx.writeAndFlush(para);
        //等待channelRead0方法获取结果后唤醒
        wait();
        return result;
    }
}
